﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Hosting;
using System.Xml;

namespace Designit.Umb.Newsletter.Bll
{
    public class MailSettings
    {
        /// <summary>
        /// Gets or sets the default name of the sender.
        /// </summary>
        /// <value>The name of the sender.</value>
        public string SenderName { get; set; }
        /// <summary>
        /// Gets or sets the default sender mail.
        /// </summary>
        /// <value>The sender mail.</value>
        public string SenderMail { get; set; }
        /// <summary>
        /// Gets or sets the pop3/smtp username.
        /// </summary>
        /// <value>The mail server username.</value>
        public string MailServerUsername { get; set; }
        /// <summary>
        /// Gets or sets the pop3/smtp password.
        /// </summary>
        /// <value>The mail server password.</value>
        public string MailServerPassword { get; set; }
        /// <summary>
        /// Gets or sets the default timezone to send from.
        /// </summary>
        /// <value>The timezone id.</value>
        public string TimezoneId { get; set; }
        /// <summary>
        /// Gets or sets the SMTP server.
        /// </summary>
        /// <value>The SMTP server.</value>
        public string SmtpServer { get; set; }
        /// <summary>
        /// Gets or sets the SMTP port.
        /// </summary>
        /// <value>The SMTP port.</value>
        public int SmtpPort { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether [SMTP auth].
        /// </summary>
        /// <value><c>true</c> if [SMTP auth]; otherwise, <c>false</c>.</value>
        public bool SmtpAuth { get; set; }
        /// <summary>
        /// Gets or sets the POP3 server.
        /// </summary>
        /// <value>The POP3 server.</value>
        public string Pop3Server { get; set; }
        /// <summary>
        /// Gets or sets the POP3 port.
        /// </summary>
        /// <value>The POP3 port.</value>
        public int Pop3Port { get; set; }
        /// <summary>
        /// Gets or sets the bounce handler interval.
        /// </summary>
        /// <value>The bounce handler interval.</value>
        public int BounceHandlerInterval { get; set; }
        /// <summary>
        /// Gets or sets a value indicating whether [soft bounce handling].
        /// </summary>
        /// <value><c>true</c> if [soft bounce handling]; otherwise, <c>false</c>.</value>
        public bool SoftBounceHandling { get; set; }
        /// <summary>
        /// Gets or sets the date and time of the last bouncehandling.
        /// </summary>
        /// <value>The last check.</value>
        public DateTime LastCheck { get; set; }
        /// <summary>
        /// Gets or sets the default mail to send test mails to.
        /// </summary>
        /// <value>The test mail.</value>
        public string TestMail { get; set; }
        /// <summary>
        /// Gets or sets the unsubscribe page.
        /// </summary>
        /// <value>The unsubscribe page.</value>
        public string UnsubscribePage { get; set; }
        /// <summary>
        /// Gets or sets the domain.
        /// </summary>
        /// <value>The domain.</value>
        public string Domain { get; set; }
        /// <summary>
        /// Gets or sets the google analytics sites.
        /// </summary>
        /// <value>The google analytics sites.</value>
        public string[] GoogleAnalyticsSites { get; set; }

        /// <summary>
        /// Gets the mail settings.
        /// </summary>
        /// <returns></returns>
        public static MailSettings Get()
        {
            MailSettings ret = null;
            var path = @"/config/designit/newsletter/mailSettings.config";
            path = HostingEnvironment.MapPath(path);
            if (path != null)
            {
                ret = new MailSettings();
                var timeZoneId = TimeZoneInfo.Local.Id;
                var doc = new XmlDocument();
                doc.Load(path);
                XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Name']");
                ret.SenderName = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
                ret.SenderMail = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
                ret.MailServerUsername = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                ret.MailServerPassword = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TimezoneId']");
                if (!string.IsNullOrEmpty(xnode.Attributes[1].Value))
                {
                    timeZoneId = xnode.Attributes[1].Value;
                }
                ret.TimezoneId = timeZoneId;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
                ret.SmtpServer = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
                ret.SmtpPort = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? 25 : Convert.ToInt32(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
                ret.SmtpAuth = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? false : Convert.ToBoolean(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3']");
                ret.Pop3Server = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3port']");
                ret.Pop3Port = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? 110 : Convert.ToInt32(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Bounce']");
                ret.BounceHandlerInterval = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? 0 : Convert.ToInt32(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SoftBounce']");
                ret.SoftBounceHandling = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? false : Convert.ToBoolean(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='LastCheck']");
                ret.LastCheck = string.IsNullOrEmpty(xnode.Attributes[1].Value) ? DateTime.MinValue : Convert.ToDateTime(xnode.Attributes[1].Value);
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TestMail']");
                ret.TestMail = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Server']");
                ret.Domain = xnode.Attributes[1].Value;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Unsubscribe']");
                ret.UnsubscribePage = xnode.Attributes[1].Value;
                //xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='ConfirmUnsubscribe']");
                //txtconfirmUnsub.Text = xnode.Attributes[1].Value;
                XmlNodeList entryElements = doc.SelectNodes("//mailSettings/trustedSites/*");
                if (entryElements != null)
                {
                    ret.GoogleAnalyticsSites = new string[entryElements.Count];
                    for(var i = 0; i < entryElements.Count; i++)
                    {
                        ret.GoogleAnalyticsSites[i] = entryElements[i].Attributes[0].Value.ToString();
                    }
                }
                else
                    ret.GoogleAnalyticsSites = new string[0];
            }
            return ret;
        }

        public static void Update(MailSettings mailSettings)
        {
            mailSettings.Update();
        }

        public void Update()
        {
            var doc = new XmlDocument();
            string path = @"/config/designit/newsletter/mailSettings.config";
            path = HostingEnvironment.MapPath(path);
            if (!string.IsNullOrEmpty(path))
            {
                doc.Load(path);
                XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Name']");
                xnode.Attributes[1].Value = SenderName;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
                xnode.Attributes[1].Value = SenderMail;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
                xnode.Attributes[1].Value = MailServerUsername;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                xnode.Attributes[1].Value = MailServerPassword;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TimezoneId']");
                xnode.Attributes[1].Value = TimezoneId;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
                xnode.Attributes[1].Value = SmtpServer;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
                xnode.Attributes[1].Value = SmtpPort.ToString();
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
                xnode.Attributes[1].Value = SmtpAuth.ToString();
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3']");
                xnode.Attributes[1].Value = Pop3Server;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='POP3port']");
                xnode.Attributes[1].Value = Pop3Port.ToString();
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Bounce']");
                xnode.Attributes[1].Value = BounceHandlerInterval.ToString();
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SoftBounce']");
                xnode.Attributes[1].Value = SoftBounceHandling.ToString();
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TestMail']");
                xnode.Attributes[1].Value = TestMail;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Server']");
                xnode.Attributes[1].Value = Domain;
                xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Unsubscribe']");
                xnode.Attributes[1].Value = UnsubscribePage;
                //xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='ConfirmUnsubscribe']");
                //xnode.Attributes[1].Value = txtconfirmUnsub.Text;
                xnode = doc.SelectSingleNode("//mailSettings/trustedSites");
                xnode.RemoveAll();
                foreach (var analyticsSite in GoogleAnalyticsSites)
                {
                    XmlNode localNode = doc.CreateNode(XmlNodeType.Element, "trustedSite", null);
                    XmlAttribute attrib = localNode.OwnerDocument.CreateAttribute("value");
                    attrib.Value = analyticsSite;
                    localNode.Attributes.Append(attrib);
                    xnode.AppendChild(localNode);
                }
                doc.Save(path);
            }
        }
    }
}
